package com.hooya.fa.eu.biz.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hooya.fa.eu.api.bo.SkuLastPriceBO;
import com.hooya.fa.eu.api.enums.CkEnum;
import com.hooya.fa.eu.api.vo.DictVO;
import com.hooya.fa.eu.biz.dao.entity.CkDict;
import com.hooya.fa.eu.biz.dao.entity.MetaWarehouse;
import com.hooya.fa.eu.biz.dao.entity.PlaceMatchDict;
import com.hooya.fa.eu.biz.dao.entity.rxh.MetaStore;
import com.hooya.fa.eu.biz.dao.manager.DictManager;
import com.hooya.fa.eu.biz.dao.mapper.CkDictMapper;
import com.hooya.fa.eu.biz.dao.mapper.DictMapper;
import com.hooya.fa.eu.biz.service.DictRelationService;
import com.hooya.integrated.common.core.util.BeanCopyUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 1
 * @Author : Zongz
 * @Copyright Copyright (c) 豪雅集团
 * @Create 2024/1/30
 * @Version 1.0.0
 */
@Slf4j
@Service
@DS("fa_eu")
@AllArgsConstructor
public class DictRelationServiceImpl implements DictRelationService {

    private final DictManager dictManager;

    private final DictMapper dictMapper;

    private final CkDictMapper ckDictMapper;

    @Override
    public List<PlaceMatchDict> getPlaceMatchList() {
        return dictMapper.getPlaceMatchList();
    }

    @Override
    public List<MetaStore> getMetaStoreList() {
        return dictMapper.getMetaStoreList();
    }

    @Override
    public Map<String, String> getMetaWarehouseMap() {
        Map<String, String> res = new HashMap<>();
        List<MetaWarehouse> metaWarehouseList = dictMapper.getMetaWarehouseList();
        if (!CollectionUtils.isEmpty(metaWarehouseList)) {
            return metaWarehouseList.stream()
                    .collect(Collectors.toMap(MetaWarehouse::getWhId, MetaWarehouse::getCountry));
        }
        return res;
    }

    @Override
    public List<DictVO> getCkDictList() {
        List<DictVO> res = new LinkedList<>();
        List<CkDict> dictList = ckDictMapper.selectList(null);
        dictManager.cacheDict(dictList);
        //deal type is listTypeList
        List<CkDict> listTypeList = dictList.stream().filter(l -> l.getType().equals(1)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(listTypeList)) {
            Map<String, List<CkDict>> map = listTypeList.stream().collect(Collectors.groupingBy(CkDict::getName));
            map.forEach((k, l) -> dictManager.dealNormalMap(res, k, k, BeanCopyUtils.copyListProperties(l, DictVO::new)));
        }
        List<CkDict> mapTypeList = dictList.stream().filter(l -> !l.getType().equals(1)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(mapTypeList)) {
            Map<String, List<CkDict>> map = mapTypeList.stream()
                    .collect(Collectors.groupingBy(l -> l.getName() + "_" + l.getType()));
            map.forEach((n, l) -> {
                String[] keyName = n.split("_");
                String name = keyName[0];
                Integer type = Integer.valueOf(keyName[1]);
                List<DictVO> child;
                if (Objects.equals(type, 2)) {
                    child = BeanCopyUtils.copyListProperties(l, DictVO::new);
                    dictManager.dealNormalMap(res, name, name, child);
                }
                if (Objects.equals(type, 3)) {
                    //deal special
                    if (CkEnum.FBA_CK_MAP.getName().equals(name)) {
                        child = BeanCopyUtils.copyListProperties(l, DictVO::new, (s, t) -> {
                            t.setParamKey(s.getParamValue());
                            t.setParamValue(s.getParamKey());
                            t.setType(CkEnum.getTypeByName(CkEnum.FBA_CK_MAP.getName()));
                            t.setIsSystem(CkEnum.getSystemFlagByName(CkEnum.FBA_CK_MAP.getName()));
                            t.setSort(null);
                        });
                        dictManager.dealNormalMap(res, name, name, child);
                        name = CkEnum.FBA_CK_REVERSAL_MAP.getName();
                    }
                    Map<String, List<CkDict>> keyMap = l.stream().collect(Collectors.groupingBy(CkDict::getParamKey));
                    DictVO parentVO = dictManager.dealNormalMap(res, name, name, new ArrayList<>());
                    String finalName = name;
                    keyMap.forEach((key, v) ->
                            dictManager.dealNormalMap(parentVO.getChildren(), key, finalName,
                                    BeanCopyUtils.copyListProperties(v, DictVO::new)));
                }
                if (Objects.equals(type, 4)) {
                    DictVO parentVO = dictManager.dealNormalMap(res, name, name, new ArrayList<>());
                    List<CkDict> parentList = l.stream()
                            .filter(d -> Objects.equals(-1, d.getParentId())).collect(Collectors.toList());
                    for (CkDict p : parentList) {
                        DictVO secondVO = dictManager
                                .dealNormalMap(parentVO.getChildren(), p.getParamKey(), name, new ArrayList<>());
                        secondVO.setId(p.getId());
                        secondVO.setParentId(p.getParentId());
                        secondVO.setSort(p.getSort());
                        List<CkDict> secondListList = l.stream()
                                .filter(d -> Objects.equals(p.getId(), d.getParentId())).collect(Collectors.toList());
                        Map<String, List<CkDict>> secondKeyMap = secondListList.stream()
                                .collect(Collectors.groupingBy(CkDict::getParamKey));
                        String finalName = name;
                        secondKeyMap.forEach((s, d) -> {
//                            DictVO thirdVO = dealNormalMap(secondVO.getChild(), s, finalName, new ArrayList<>());
                            dictManager.dealNormalMap(secondVO.getChildren(), s, finalName,
                                    BeanCopyUtils.copyListProperties(d, DictVO::new));
                        });
                    }
                }
            });
        }
        return res;
    }

    @Override
    public void add(DictVO dict) {
        dictManager.checkTypeParam(dict);
        if (Objects.isNull(dict.getParentId())) {
            dict.setParentId(0);
        }
        ckDictMapper.insert(BeanCopyUtils.copyPropertiesNew(dict, CkDict::new));
    }

    @Override
    @Transactional
    @CacheEvict(value = {"dict"}, key = "#dict.name")
    public void edit(DictVO dict) {
        dictManager.checkTypeParam(dict);
        ckDictMapper.updateById(BeanCopyUtils.copyPropertiesNew(dict, CkDict::new));
    }

    @Override
    @Transactional
    @CacheEvict(value = {"dict"}, key = "#name")
    public void delete(Integer id, String name) {
        CkDict ckDict = ckDictMapper.selectById(id);
        if (Objects.isNull(ckDict)) {
            throw new RuntimeException("不存在仓库字典");
        }
        if (ckDict.getParentId() == -1) {
            List<CkDict> dictList =
                    ckDictMapper.selectList(Wrappers.<CkDict>lambdaQuery().eq(CkDict::getParentId, ckDict.getId()));
            if (!CollectionUtils.isEmpty(dictList)) {
                ckDictMapper.deleteBatchIds(dictList);
            }
        }
        ckDictMapper.deleteById(id);
    }

    @Override
    public List<SkuLastPriceBO> getSkuLastPriceInfo(String date) {
        List<SkuLastPriceBO> res = ckDictMapper.getSkuLastPriceInfo(date);
        if (CollectionUtils.isEmpty(res)) {
            return new ArrayList<>();
        }
        return res;
    }

}
